<template>
	<el-drawer direction="rtl" :title="dialogTitle" v-model="dialogVisible" size="90%">
		<el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px" v-loading="formLoading">
			<el-row>
				<el-col :span="12">
					<el-form-item label="所属社区" prop="commId">
						<el-tree-select v-model="formData.commId" :data="communityTree" :props="defaultProps" check-strictly default-expand-all placeholder="请选择所属社区" value-key="id" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="中间件" prop="netSysId">
						<el-select v-model="formData.netSysId" placeholder="请选择中间件" clearable>
							<el-option v-for="n in sysConfigList" :key="n.id" :label="n.community.name" :value="n.id" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="套餐类型" prop="packType">
						<el-select v-model="formData.packType" placeholder="请选择套餐类型">
							<el-option v-for="dict in netPackageArr" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="运营商" prop="serviceProvider">
						<el-select v-model="formData.serviceProvider" placeholder="请选择运营商">
							<el-option v-for="dict in netOperatorArr" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="凌风系统套餐id" prop="lfPackId" style="display: flex; align-items: center">
						<el-input type="number" v-model.trim="formData.lfPackId" placeholder="请输入凌风系统套餐id" style="flex: 1" />
						<el-button style="margin-left: 20px" @click="changePackage" type="primary" v-if="btnShow">获得凌风系统的套餐信息</el-button>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="上网模式" prop="netMode">
						<el-select v-model="formData.netMode" placeholder="请选择上网模式">
							<el-option v-for="n in netPackageAttributesArr" :key="n.value" :label="n.label" :value="n.value" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="房产" prop="houseId">
				<el-select v-model="formData.houseId" filterable remote placeholder="请选择相关房产" clearable :remote-method="remoteHouse">
					<el-option v-for="item in houseList" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="捆绑套餐" prop="bindPackId">
				<el-select v-model="formData.bindPackId" multiple filterable remote placeholder="请选择相关套餐" clearable :remote-method="remoteList">
					<el-option v-for="item in pageLisrt" :key="item.id" :label="item.packName" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="套餐名称" prop="packName">
						<el-input type="string" v-model.trim="formData.packName" placeholder="请输入套餐名称" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="价格（元）" prop="price">
						<el-input type="number" v-model.trim="formData.price" placeholder="请输入价格（元）" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="时长" prop="duration">
						<el-input type="number" v-model.trim="formData.duration" placeholder="请输入时长">
							<template #prepend>
								<el-select v-model="kType" placeholder="请选择" class="!w-120px">
									<el-option label="天" value="day" />
									<el-option label="月" value="month" />
									<el-option label="年" value="year" />
								</el-select>
							</template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="速度（MB）" prop="speed">
						<el-input type="number" v-model.trim="formData.speed" placeholder="请输入速度（MB）" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="购买次数限制" prop="buyTimes">
						<el-input type="number" v-model.trim="formData.buyTimes" placeholder="请输入购买次数限制" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="排序" prop="sort">
						<el-input type="number" v-model.trim="formData.sort" placeholder="请输入排序" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="子账号数量">
						<el-input type="number" v-model.trim="formData.childCount" placeholder="请输入子账号数量" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="备注说明">
						<el-input v-model.trim="formData.remark" placeholder="请输入备注说明" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="允许续费" prop="isReNew">
						<el-select v-model="formData.isReNew" placeholder="请选择是否允许续费">
							<el-option label="不允许" :value="0" />
							<el-option label="允许" :value="1" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="到期后才能购买" prop="isLimitByValidityPeriod">
						<el-select v-model="formData.isLimitByValidityPeriod" placeholder="请选择是否是否有效期到期后才能购买">
							<el-option label="不限制" :value="0" />
							<el-option label="限制" :value="1" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="状态" prop="packStatus">
						<el-select v-model="formData.packStatus" placeholder="请选择状态">
							<el-option label="正常" :value="1" />
							<el-option label="停用" :value="2" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="购买正式套餐" prop="isNeedPurchaseOfficialPackageFirst">
						<el-select v-model="formData.isNeedPurchaseOfficialPackageFirst" placeholder="请选择是否购买正式套餐">
							<el-option label="不需要" :value="0" />
							<el-option label="需要" :value="1" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
			<el-button @click="dialogVisible = false">取 消</el-button>
		</template>
	</el-drawer>
</template>
<script setup lang="ts">
	import * as CommunityApi from '@/api/zwsj/community'
	import { defaultProps, handleTree } from '@/utils/tree'
	import * as NetPackageApi from '@/api/zwsj/netPackage'
	import { getNetSysConfigs } from '@/api/zwsj/netSysConfig'
	import { divide, convertSecondsToUnit } from '@/utils/tools'
	import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
	import * as houseRoom from '@/api/zwsj/houseRoom'

	const { t } = useI18n() // 国际化
	const formRef = ref() // 表单 Ref
	const message = useMessage() // 消息弹窗
	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		commId: null,
		netSysId: null,
		lfPackId: null,
		packType: null,
		packName: null,
		serviceProvider: null,
		price: null,
		duration: null,
		speed: null,
		sort: null,
		remark: null,
		buyTimes: 0,
		packStatus: 1,
		houseId: null,
		bindPackId: [],
		bindPackageList: null,
		houseDO: null,
		childCount: 0,
		netMode: 1,
		isReNew: 0, // 是否允许续费
		isNeedPurchaseOfficialPackageFirst: 0, // 是否需要先购买官方套餐
		isLimitByValidityPeriod: 0, // 是否有效期到期后才能购买
	})

	const netPackageArr = getIntDictOptions(DICT_TYPE.NET_PACKAGE) //宽带套餐类型
	const netOperatorArr = getIntDictOptions(DICT_TYPE.NET_OPERATOR) //宽带运营商
	const netPackageAttributesArr = getIntDictOptions(DICT_TYPE.PACKAGE_ATTRIBUTES) // 宽带套餐属性

	const formRules = reactive({
		commId: [{ required: true, message: '社区不能为空', trigger: 'blur' }],
		netSysId: [{ required: true, message: '中间件不能为空', trigger: 'blur' }],
		lfPackId: [{ required: true, message: '凌风系统套餐id不能为空', trigger: 'blur' }],
		packType: [{ required: true, message: '套餐类型不能为空', trigger: 'blur' }],
		packName: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }],
		serviceProvider: [{ required: true, message: '运营商不能为空', trigger: 'blur' }],
		price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
		duration: [{ required: true, message: '时长不能为空', trigger: 'blur' }],
		speed: [{ required: true, message: '速度（MB）不能为空', trigger: 'blur' }],
		buyTimes: [{ required: true, message: '购买次数限制不能为空', trigger: 'blur' }],
		netMode: [{ required: true, message: '上网模式不能为空', trigger: 'blur' }],
		isLimitByValidityPeriod: [{ required: true, message: '到期后才能购买不能为空', trigger: 'blur' }],
		isReNew: [{ required: true, message: '允许续费不能为空', trigger: 'blur' }],
		isNeedPurchaseOfficialPackageFirst: [{ required: true, message: '购买正式套餐不能为空', trigger: 'blur' }],
		packStatus: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
	})
	const communityTree = ref() // 树形结构
	const sysConfigList = ref([])
	const kType = ref('day')
	const houseList = ref([])
	const pageLisrt = ref([])
	const btnShow = ref(true)
	/** 打开弹窗 */
	const open = async (type: string, id?: number, commId?: number, serviceProvider?: number) => {
		btnShow.value = true
		dialogVisible.value = true
		dialogTitle.value = t('action.' + type)
		formType.value = type
		resetForm()
		getMiddlewareList()

		//设置区域默认值
		formData.value.commId = commId || ''

		if (serviceProvider) {
			formData.value.serviceProvider = serviceProvider
		}

		// 修改时，设置数据
		if (id) {
			btnShow.value = false
			formLoading.value = true
			try {
				formData.value = await NetPackageApi.getPackage(id)
				const arr = convertSecondsToUnit(formData.value.duration) || []
				kType.value = arr[0] || 'day'
				formData.value.duration = arr[1]
				formData.value.price = divide(formData.value.price, 100)

				if (formData.value.houseDO) {
					houseList.value.push(formData.value.houseDO)
				}

				const bindPackIdArr = formData.value.bindPackId || ''
				formData.value.bindPackId = bindPackIdArr.length > 0 ? bindPackIdArr.split(',').map(item => Number(item)) : []

				if (formData.value.bindPackageList) {
					pageLisrt.value = formData.value.bindPackageList || []
				}
			} finally {
				formLoading.value = false
			}
		}
		// 获得社区树
		await getTree()
	}
	defineExpose({ open }) // 提供 open 方法，用于打开弹窗

	//获取中间件列表
	const getMiddlewareList = async () => {
		getNetSysConfigs().then(data => {
			sysConfigList.value = data
			formData.value.netSysId = data[0]?.id
		})
	}

	/** 获得区域树 */
	const getTree = async () => {
		communityTree.value = []
		const data = await CommunityApi.listSimpleCommunitys()
		let community: Tree = { id: 0, name: '顶级区域', children: [] }
		community.children = handleTree(data)
		communityTree.value.push(community)
	}
	const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

	const submitForm = async () => {
		// 校验表单
		if (!formRef) return
		const valid = await formRef.value.validate()
		if (!valid) return
		const duration = Number(formData.value.duration)
		if (isNaN(duration)) {
			message.error('时长必须为数字')
			return
		}
		if (!Number.isInteger(duration)) {
			message.error('时长必须为整数')
			return
		}

		const value = convertToSeconds(kType.value, duration)
		if (!value) {
			message.error('时长不能大于一百年')
			return
		}

		if (formData.value.bindPackId) {
			formData.value.bindPackId = formData.value.bindPackId.join(',')
		}

		formData.value.duration = value
		formData.value.price = Number(formData.value.price) * 100
		// 提交请求
		formLoading.value = true
		try {
			if (!formData.value.houseId) {
				formData.value.houseId = 0
			}
			const data = formData.value as unknown as NetPackageApi.NetPackageVO
			if (formType.value === 'create') {
				await NetPackageApi.createPackage(data)
				message.success(t('common.createSuccess'))
			} else {
				await NetPackageApi.updatePackage(data)
				message.success(t('common.updateSuccess'))
			}
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}

	/**
	 * 计算时间,并判断是否大于一百年，返回秒数
	 * @param type 类型
	 * @param time 时间
	 */
	const convertToSeconds = (type: string, time: number | string) => {
		const secondsIn100Years = 100 * 365 * 24 * 60 * 60
		let value = Number(time)
		if (type == 'day') {
			value = value * 24 * 60 * 60
		} else if (type == 'month') {
			value = value * 30 * 24 * 60 * 60
		} else if (type == 'year') {
			value = value * 365 * 24 * 60 * 60
		}

		if (value > secondsIn100Years) {
			return false
		} else {
			return value
		}
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			commId: null,
			netSysId: null,
			lfPackId: null,
			packType: null,
			packName: null,
			serviceProvider: null,
			price: null,
			duration: null,
			speed: null,
			sort: null,
			remark: null,
			buyTimes: 0,
			packStatus: 1,
			houseId: null,
			bindPackId: [],
			bindPackageList: null,
			houseDO: null,
			childCount: 0,
			netMode: 1,
			isReNew: 0, // 是否允许续费
			isNeedPurchaseOfficialPackageFirst: 0, // 是否需要先购买官方套餐
			isLimitByValidityPeriod: 0, // 是否有效期到期后才能购买
		}
		formData.value.packType = netPackageArr[0].value || null
		formData.value.serviceProvider = netOperatorArr[0].value || null
		formRef.value?.resetFields()
		houseList.value = []
		pageLisrt.value = []
	}

	const remoteHouse = async (query: string) => {
		try {
			if (query) {
				if (!formData.value.commId) {
					message.error('请先选择社区')
					return
				}
				houseList.value = []
				const data = {
					commId: formData.value.commId,
					keyWord: query,
					pageNo: 1,
					pageSize: 100,
					parentId: 0,
				}
				const res = await houseRoom.getHouseRoomPage(data)
				houseList.value = res.list || []
				return
			}
		} finally {
		}
	}

	const remoteList = async (query: string) => {
		try {
			if (query) {
				const queryParams = {
					pageNo: 1,
					commId: formData.value.commId,
					pageSize: 100,
					netSysId: formData.value.netSysId,
					packName: query,
					serviceProvider: null,
					packType: null,
				}

				const data = await NetPackageApi.getPage(queryParams)
				pageLisrt.value = data.list || []
			}
		} catch (error) {}
	}

	const changePackage = async () => {
		if (!formData.value.netSysId) {
			message.error('请先选择中间件')
			return
		}
		if (!formData.value.lfPackId) {
			message.error('请先输入凌风系统套餐id')
			return
		}
		NetPackageApi.getLfPackage({ netSysId: formData.value.netSysId, packageId: formData.value.lfPackId }).then(res => {
			const packageObj = res || null
			if (!packageObj) {
				message.error('未查询到该套餐')
				return
			}
			formData.value.packName = packageObj.servername
			formData.value.price = packageObj.price
			kType.value = packageObj.expirationtype
			formData.value.duration = packageObj.expirationdate
			formData.value.speed = extractBandwidth(packageObj.servername)
			// 运营商 + 速度  + 时间  = 排序号
			formData.value.sort = formatInternetInfo(formData.value.serviceProvider, formData.value.speed, kType.value, formData.value.duration)
		})
	}

	/**
	 * 从字符串中提取带宽信息并处理单位转换
	 * @param {string} str - 包含带宽信息的字符串，如"下板安控云速联通200M(月)"、"新垵联通50兆包年(FTTB)"
	 * @returns {number | null} 处理后的带宽信息，如200、1000或50
	 */
	const extractBandwidth = (str: string) => {
		// 正则表达式匹配数字加单位(M、G或兆)的模式
		const regex = /(\d+)([MG]|兆)/
		const match = str.match(regex)

		if (!match) {
			return null // 如果没有匹配到，返回null
		}

		const value = parseInt(match[1], 10)
		const unit = match[2]

		// 单位转换：G转M（1G=1000M），M和兆直接返回数值
		if (unit === 'G') {
			return value * 1000
		} else {
			// 处理M或兆的情况
			return value
		}
	}

	/**
	 * 从字符串中拼接，运营商、速度、时间类型、时间为排序号
	 * @param {string} operator - 运营商，如"联通"
	 * @param {number} bandwidthMB - 带宽MB，如200
	 * @param {string} timeType - 时间类型，如"month"
	 * @param {number} time - 时间，如1
	 * @returns {string } 处理后的排序号 3020001
	 */
	const formatInternetInfo = (operator: string | number, bandwidthMB: number, timeType: string, time: number) => {
		// 处理宽带MB：转换为字符串，不足4位前面补零
		let bandwidthStr = String(bandwidthMB)
		// 确保不超过4位（如果超过则截断，根据需求"最多四位长度"）
		if (bandwidthStr.length > 4) {
			bandwidthStr = bandwidthStr.substring(0, 4)
		}
		// 不足4位前面补零
		bandwidthStr = bandwidthStr.padStart(4, '0')

		// 处理时间：转换为数字
		let timeNum = Number(time)
		// 如果是年份，转换为月份
		if (timeType === 'year') {
			timeNum *= 12
		}
		// 转换为字符串，不足2位前面补零
		let timeStr = String(timeNum).padStart(2, '0')

		// 拼接结果并返回
		return `${operator}${bandwidthStr}${timeStr}`
	}

	// onMounted(() => {
	//   // 组件挂载后的逻辑
	// });
</script>
<style lang="scss" scoped></style>
